import tensorflow as tf
from tensorboard.backend.event_processing import event_accumulator


def extract_scalars(file_path):
    ea = event_accumulator.EventAccumulator(file_path)
    ea.Reload()

    # 获取所有标量的标签
    scalar_tags = ea.Tags()['scalars']
    scalars = {}

    for tag in scalar_tags:
        scalars[tag] = []
        # 获取该标签所有步骤上的值
        for scalar_event in ea.Scalars(tag):
            scalars[tag].append((scalar_event.step, scalar_event.value))
    print(scalars.keys())
    return scalars


def find_best_step_for_iou(scalars, iou_tag='IOU'):
    if iou_tag not in scalars:
        raise ValueError(f"Tag '{iou_tag}' not found in the event file.")

    best_step, best_value = max(scalars[iou_tag], key=lambda x: x[1])
    return best_step


def get_values_at_step(scalars, step):
    values_at_step = {}
    for tag, values in scalars.items():
        for s, value in values:
            if s == step:
                values_at_step[tag] = value
                break
    return values_at_step


# file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240523_175936"
# file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240522_211009"
# file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240522_125333"
# file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240521_190749"
# file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240414_191502"
file_path = "run/Low_Contrast_Roads/CoANet-resnet/experiment_20240524_063207"

iou_tag = 'val/IoU'  # 如果你的IOU标签是其他名字，修改这个值

scalars = extract_scalars(file_path)
best_step = find_best_step_for_iou(scalars, iou_tag)
values_at_best_step = get_values_at_step(scalars, best_step)

print(f"Best IOU at step {best_step}:")
for tag, value in values_at_best_step.items():
    print(f"{tag}: {value}")